<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="params.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          clearable
          @input="searchEmployee"
          @clear="clear"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="{ label: 'name' }"
          default-expand-all
          highlight-current
          node-key="id"
          :expand-on-click-node="false"
          @current-change="nodeClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData">
          <el-table-column label="头像" prop="staffPhoto" align="center">
            <template #default="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                :size="30"
              />
              <span v-else class="username">{{ row.username?.[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{
                row.formOfEmployment === 1
                  ? "正式"
                  : row.formOfEmployment === 2
                    ? "非正式"
                    : "未知"
              }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            sortable
            width="180"
          />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查询</el-button>
              <el-button type="text" size="mini" @click="showAssignDialog(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left:10px">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="params.page"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float: right; margin-top: 10px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <import-excel :show-excel-dialog.sync="showExcelDialog" @reload="getEmployees" />
    </div>
    <el-dialog title="分配角色" :visible.sync="showDialog">
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <div style="text-align:center">
        <el-button size="mini" type="primary" @click="assignRole">确定</el-button>
        <el-button size="mini">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let timer = null
import { reqGetDepts } from '@/api/department'
import { translateToTreeData } from '@/utils'
import { reqGetEmployees, reqExportExcel, reqDelEmployee, reqGetDetail, reqAssignRole } from '@/api/employee'
import { reqGetEnableRoles } from '@/api/role'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      roles: [], // 分配角色列表的数组
      checkList: [], // 选中角色列表的数组
      showDialog: false, // 控制分配角色的弹出框
      showExcelDialog: false, // 控制表格导入的弹出框
      total: 0,
      treeData: [], // 树形数据
      tableData: [], // 表格数据
      params: {
        page: 1,
        pagesize: 2,
        departmentId: null,

        keyword: ''
      }
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    async getDepts() {
      const { data } = await reqGetDepts()
      // console.log(data);
      this.treeData = translateToTreeData(data, 0)
      this.params.departmentId = this.treeData[0].id
      await this.$nextTick()
      this.$refs.treeRef.setCurrentKey(this.params.departmentId)
      this.getEmployees()
    },
    async getEmployees() {
      const {
        data: { rows, total }
      } = await reqGetEmployees(this.params)
      console.log(rows)
      this.total = total

      this.tableData = rows
    },
    handleSizeChange(val) {
      this.params.pagesize = val
      this.getEmployees()
    },
    handleCurrentChange(val) {
      this.params.page = val
      this.getEmployees()
    },
    // 点击部门查看员工列表
    nodeClick(data) {
      this.params.departmentId = data.id
      this.params.page = 1

      this.getEmployees()
    },
    // 输入框搜索
    searchEmployee() {
      if (!this.params.keyword.trim()) return
      this.params.page = 1
      clearTimeout(timer)
      timer = setTimeout(async() => {
        await this.getEmployees()
      }, 1000)
    },
    clear() {
      this.params.page = 1
      this.params.departmentId = this.treeData[0].id
      this.getEmployees()
    },
    // excel导出
    async  exportExcel() {
      const res = await reqExportExcel(this.tableData)
      console.log(res)
      FileSaver.saveAs(res, '员工列表.xlsx')
    },
    // 删除
    async delEmployee(id) {
      await reqDelEmployee(id)
      if (this.tableData.length === 1 && this.params.page > 1) {
        this.params.page--
      }
      this.getEmployees()
    },
    // 获取启用角色列表
    async showAssignDialog(id) {
      this.id = id

      // const res = await reqGetEnableRoles()
      // this.roles = res.data
      // const { data } = await reqGetDetail(id)
      // console.log(data)
      // 如何以最快的速度拿到多个并发请求的数据
      // Promise.all的参数和值得结果是一一对应得
      await Promise.all([reqGetEnableRoles(), reqGetDetail(id)]).then(values => {
        console.log(values)
        this.roles = values[0].data
        this.checkList = values[1].data.roleIds
        this.showDialog = true
      })
    },
    // 修改角色角色权限
    async  assignRole() {
      await reqAssignRole(this.id, this.checkList)
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
